import urllib.request
import json
import gzip
import io
import pandas as pd
import requests
import time
import csv
import datetime
from Logger import logger
d=datetime.datetime.now()
import datetime
class Weather:
    def fetch_weather(longitude,latitude):
        """
        调取某地的天气情况

        Args:
            longitude:经度
            latitude:纬度
         """
        longitude=str(int(longitude))
        latitude=str(int(latitude))
        api_url = "https://ku3h2pmk79.re.qweatherapi.com/v7/weather/now?location="+longitude+","+latitude+"&key=**********"
        logger.info(f"INPUT:longitude={longitude},latitude={latitude},url={api_url}")
        try:
            with urllib.request.urlopen(api_url) as response:
                data = response.read()
            with io.BytesIO(data) as f:
                with gzip.GzipFile(fileobj=f) as gz:
                    decompressed = gz.read()
            json_data = json.loads(decompressed)
            # Extract weather information from the response
            weather_info = json_data.get('now', {})
            temp = weather_info.get('temp', 'N/A')
            feels_like = weather_info.get('feels_like', 'N/A')
            logger.info(f"OUTPUT:longitude={longitude},latitude={latitude},temp={temp},feels_like={feels_like}")
            # Print the weather details
            return ("Temperature is {0}°C, Feels like {1}°C".format(temp,feels_like))
        except Exception as e:
             return("An error occurred while fetching weather: {0}".format(e))
    def gaode(addr):
        """
        调取某地的经纬度
        Args:
          addr:地址名
        """
        para = {
               'key':'9b07be1fbba5d6a3ef8251d127cb8797',  #高德地图开放平台申请的key
              'address':addr #传入地址参数
              }
        url = 'https://restapi.amap.com/v3/geocode/geo?' #高德地图API接口
        logger.info(f"INPUT:addr={addr},url={url}")
        req = requests.get(url,para)
        req = req.json()
        print('-' * 30)
        m = req['geocodes'][0]['location']
        logger.info(f"OUTPUT:addr={addr},location={m}")
        return m